package com.itheima.web.filters;

import com.github.pagehelper.util.StringUtil;
import com.itheima.domain.system.SysLog;
import com.itheima.domain.system.User;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日志
 */
public class LogFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        User user = (User)request.getSession().getAttribute("user");
        if (user!=null){
        String id = user.getId();

        String username = user.getUserName();

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(date);

        String ip = request.getRemoteAddr();

        String uri = request.getRequestURI();
        int i = uri.lastIndexOf("/");

        String method = uri.substring(i+1);
        StringBuffer url = request.getRequestURL();

        SysLog sysLog = new SysLog();
        sysLog.setId(id);
        sysLog.setUsername(username);
        sysLog.setTime(time);
        sysLog.setIp(ip);
        sysLog.setMethod(method);
        sysLog.setAction(url.toString());
        filterChain.doFilter(request,response);
        }else {
         request.getRequestDispatcher("请先登录");
        }
    }

    @Override
    public void destroy() {

    }

}
